package com.kim.ping.Controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.UUID;

/**
 * @ClassName: Controller
 * @Description:
 * @Author: Kim
 * @Version: 1.0
 * @Date: 2024/11/2 17:29
 **/

public class PingServiceImpl {

    private String PONG_SERVICE_URL = "http://localhost:8082/pong";
    private File RATE_LIMIT_FILE_1 = new File("D:\\ping_rate_limiter_1.file");
    private File RATE_LIMIT_FILE_2 = new File("D:\\ping_rate_limiter_2.file");

    private Logger logger = LoggerFactory.getLogger(PingServiceImpl.class);

    @Autowired
    RestTemplate restTemplate;


    @Scheduled(fixedRate = 1000)
    public void sayHello() {
        String trackingNumber = UUID.randomUUID().toString();
        FileChannel fileChannel = null;
        FileLock lock = null;
        try {
            // try to get file lock 1
            FileOutputStream fileOutputStream = new FileOutputStream(RATE_LIMIT_FILE_1);
            fileChannel = fileOutputStream.getChannel();
            logger.info(" try to get fileLock 1");
            lock = fileChannel.tryLock();

            // file lock 1 is lock try to file lock 2
            if(lock == null){
                logger.info(trackingNumber + ": get fileLock 1 fail, try to get fileLock 2");
                fileChannel.close();
                fileChannel = new FileOutputStream(RATE_LIMIT_FILE_2).getChannel();
                lock = fileChannel.tryLock();
            }

            // all file is lock do nothing
            if(lock == null){
                logger.info(trackingNumber + ": get fileLock 2 fail");
                logger.info(trackingNumber + ": All file is lock, do nothing");
                return;
            }

            ResponseEntity<String> response = restTemplate.getForEntity(PONG_SERVICE_URL, String.class);
            if(response!=null){
                logger.info(trackingNumber + ": resp:{}",response.getBody());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (lock != null && lock.isValid()) {
                try {
                    lock.release();
                    fileChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
